//
//  RequestHandle.m
//  suishouxiu
//
//  Created by parkin on 15/5/27.
//  Copyright (c) 2015年 zhongyan. All rights reserved.
//

#import "RequestHandle.h"

#import "LoginViewController.h"
//#import "UIView+Toast.h"
//#import "SSXTabBarViewController.h"

@implementation RequestHandle : NSObject 
+ (void)startOperationWithRequest:(BaseRequest *)request
                         complete:(CompleteBlock)completeBlock
                            error:(ErrorBlock)errorBlock {
    
    AFHTTPRequestOperationManager * manager = [[AFHTTPRequestOperationManager alloc] init];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/plain", nil];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
//    manager.requestSerializer.timeoutInterval = 10;
    //NSLog(@"url = %@", [request getRequestURL]);
    //NSLog(@"param = %@", [request getRequestParams]);
    //NSLog(@"method = %lu", (long)[request getRequestMethod]);
    
    if([request getRequestMethod] == PutMethod)
    {
        [manager PUT:[request getRequestURL] parameters:[request getRequestParams] success:^(AFHTTPRequestOperation *operation, id responseObject) {
            // NSLog(@"%@",responseObject);
            [self doResponseWithResponseDictionary:responseObject complete:completeBlock error:errorBlock];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            errorBlock(error);
            
        }];
    }
    else if ([request getRequestMethod] == GetMethod) {
        [manager GET:[request getRequestURL] parameters:[request getRequestParams] success:^(AFHTTPRequestOperation *operation, id responseObject) {
            //NSLog(@"%@",responseObject);
            [self doResponseWithResponseDictionary:responseObject complete:completeBlock error:errorBlock];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            errorBlock(error);
            
        }];
    } else if ([request getRequestMethod] == DeleteMethod) {
        
        [manager DELETE:[request getRequestURL] parameters:[request getRequestParams] success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            [self doResponseWithResponseDictionary:responseObject complete:completeBlock error:errorBlock];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@", error);
            errorBlock(error);
        }];
    } else{
        [manager POST:[request getRequestURL] parameters:[request getRequestParams] success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            [self doResponseWithResponseDictionary:responseObject complete:completeBlock error:errorBlock];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"%@", error);
            errorBlock(error);
        }];
    }
}

+(void)doResponseWithResponseDictionary:(id)responseObject
                                  complete:(CompleteBlock)completeBlock
                                    error:(ErrorBlock)errorBlock {
    NSDictionary *reponseDictionary = (NSDictionary *)responseObject;
    NSString *status = [reponseDictionary objectForKey:@"status"];
    
    if ([status isEqualToString:@"fail"]) {
        NSInteger error_code = [[reponseDictionary objectForKey:@"error_code"] integerValue];
        if (error_code == ERROR_PARA_VERIFIY) {
            
            //当前用户在别处登录，请重新登录
            if([MyGlobal sharedVariables].isReLogin == YES){
                //获取当前的控制器，即数组末尾
                UINavigationController *rootNavController = [AppDelegate shareInstance].navController;
                NSUInteger count = [rootNavController.viewControllers count];
                
               //[rootNavController popToRootViewControllerAnimated:NO];
                
                RepeatLoginController *controller = [[RepeatLoginController alloc] init];
                UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
                controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
                [[rootNavController.viewControllers objectAtIndex:(count-1)] presentViewController:nav animated:YES completion:^{
                    NSLog(@"");
                }];
            }
            
        }
        
        NSString *error_message = [AppError messageForErrorCode:error_code];
        NSError *error = [NSError errorWithDomain:AppErrorDomain code:error_code userInfo:@{NSLocalizedDescriptionKey:error_message}];
        errorBlock(error);
        
    }else{
        completeBlock(responseObject);
    }
    
}

+(void)uplaodImageOperationWithRequest:(BaseRequest *)request uploadData:(NSData *)uploadData
                              complete:(CompleteBlock)completeBlock
                                 error:(ErrorBlock)errorBlock {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    [manager POST:[request getRequestURL] parameters:[request getRequestParams] constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileData:uploadData name:@"file" fileName:@"pic" mimeType:@"image/jpg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"%@",responseObject);
        
        [self doResponseWithResponseDictionary:responseObject complete:completeBlock error:errorBlock];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
        errorBlock(error);
    }];


}


+ (void)startUploadOperationWithRequest:(id<SSXRequestProtocol>)request
                               fileName:(NSString *)fileName
                             uploadData:(NSData *)uploadData
                             originData:(NSData *)originData
                               complete:(CompleteBlock)completeBlock
                                  error:(ErrorBlock)errorBlock {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/plain", nil];
    [manager POST:[request getRequestURL] parameters:[request getRequestParams] constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        [formData appendPartWithFileData:uploadData name:@"file" fileName:@"upload.jpg" mimeType:@"image/jpg"];
        [formData appendPartWithFileData:originData name:@"file" fileName:@"origin.jpg" mimeType:@"image/jpg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"%@",responseObject);
        
        //[self doResponseWithResponseDictionary:responseObject complete:completeBlock error:errorBlock];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@", error);
        errorBlock(error);
    }];
}
@end
